<?php

namespace IDock\Insurance\ZSIC\Response;

use IDock\Http\Request;
use IDock\Http\Response;

class AllZSICResponse extends Response
{

    protected $status = '';

    protected $logicStatus = '';

    public function resolve(): Response
    {
        $body = $this->getBody();
        if ($this->printer) {
            $this->printer = new $this->printer;
        }
        if ($body) {
            $xml_parser = xml_parser_create();
            if(!xml_parse($xml_parser,$body,true)){
                xml_parser_free($xml_parser);
                $this->setError(  '保险公司返回格式异常');
                return  $this;
            }
            $xml = simplexml_load_string($body);
            $body = $this->objectToArray($xml);
            $errorMsg = $body['head']['resultCode'] ?? '';
            $message = $body['head']['errorMsg'] ?? '';
            $this->setBody($body);
            if ($errorMsg != '1') {
                $this->setError(  ($errorMsg ?: '') .":".$message);
                return  $this;
            }
        }

        return $this;
    }

    public function objectToArray($object) {
        if( count($object)==0 )  return trim((string)$object);
        $result = array();
        $object = is_object($object) ? get_object_vars($object) : $object;
        foreach ($object as $key => $val) {
            $val = (is_object($val) || is_array($val)) ? $this->objectToArray($val) : $val;
            $result[$key] = $val;
        }
        return $result;
    }

    /**
     * @return string
     */
    public function getState(): string
    {
        return $this->get('state','');
    }

    /**
     * @return string
     */
    public function getMsg(): string
    {
        return $this->get('msg','');
    }

    /**
     * 格式化数组为多维
     * @param array $arr
     * @return array
     */
    public function formatArray(array $arr)
    {
        if(empty($arr)) return $arr;
        if(!isset($arr[0])){
            $tmp = $arr;
            unset($arr);
            $arr[] = $tmp;
        }
        return $arr;
    }

}
